package com.mashibing.juc.c_000;

public class T05_Join_Lock {

    public static void main(String[] args) {

//        MyThread1 myThread1 = new MyThread1();
//        myThread1.start();
//
//        synchronized (myThread1) {
//            for (int i = 0; i < 10; i++) {
//                System.out.println("main-" + i);
//                try {
//                    Thread.sleep(500);
//                    if (i == 5) myThread1.join();
                    // myThread1.join() ==>> myThread1.wait() ==>> Object.wait() 释放的锁对象时this
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }

        Object lock = new Object();
        MyThread2 myThread2 = new MyThread2(lock);
        myThread2.start();

        synchronized (lock) {
            for (int i = 0; i < 10; i++) {
                System.out.println("main-" + i);
                try {
                    Thread.sleep(500);
                    if (i == 5) myThread2.join();
                    // myThread2.join() ==>> myThread2.wait() ==>> Object.wait() 释放的锁对象时this
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    static class MyThread1 extends Thread {

        @Override
        public void run() {
            synchronized (this) {
                for (int i = 0; i < 10; i++) {
                    System.out.println("MyThread1-" + i);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

    }

    static class MyThread2 extends Thread {
        private Object lock;

        public MyThread2(Object lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            synchronized (lock) {
                for (int i = 0; i < 10; i++) {
                    System.out.println("MyThread2-" + i);
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }

    }

}
